//专门用来存放关于日志的所有接口
const Router = require('koa-router'); //引入路由
const journal = new Router();
const db = require('../utils/db');
const bodyparser = require('koa-bodyparser');
//写对应的接口

journal.use(bodyparser())

//后台获得所有用户日志信息
journal.get('/',async ctx=>{
    let data = await new Promise((reslove,reject) => {
        return db.query(`select * from journal_class`,(err,data) => {
            if(err) console.log(err);
            reslove(data);
        })
    })
    ctx.body = data;
})

//前端获取一个用户的所有日志
journal.post('/qianduan',async ctx=>{
    const data = ctx.request.body;
    const getSql = `select * from journal_class where openId ='${data.openId}'`
    let result = await new Promise ((reslove,reject)=>{
        return db.query(getSql,(err,data)=>{
	    if(err) console.log(err);
	    reslove(data);
	    })
    })
    ctx.body = result;
})


//新日志
journal.post('/insert',async ctx =>{
    const data = ctx.request.body;
    const insertSql = `insert into journal_class 
    (openid,time,name,content,img) values ("${data.openid}","${data.time}","${data.name}","${data.content}","${data.img}")`
    let result = await new Promise ((reslove,reject)=>{
        return db.query(insertSql,(err,data)=>{
            if(err) console.log(err);
            reslove(data)
        })
    })
    ctx.body = "保存成功";
})

//修改日志
journal.post('/modify',async ctx =>{
    const data = ctx.request.body;
    const updateSql = `update journal_class set name="${data.name}",content="${data.content}",time="${data.time}",img="${data.img}" 
    where openId="${data.openId}" and id=${data.id})`
    let result = await new Promise ((reslove,reject)=>{
        return db.query(updateSql,(err,data)=>{
            if(err) console.log(err);
            reslove(data)
        })
    })
    ctx.body = "修改成功";
})



//删除日志
journal.post('/delete',async ctx =>{
    const data = ctx.request.body;
    const deleteSql = 
    `delete from journal_class where 
    openId="${data.openId}" and id=${data.id}`
    let result = await new Promise ((reslove,reject)=>{
        return db.query(deleteSql,(err,data)=>{
            if(err) console.log(err);
            reslove(data)
        })
    })
    ctx.body = "删除成功";
})


//删除日志后的id变化
journal.post('/modify1',async ctx =>{
    const data = ctx.request.body;
    const updateSql = `update journal_class set name="${data.name}",content="${data.content}",time="${data.time}",img="${data.img}",id=${data.id-1} 
    where openId="${data.openId}" and id=${data.id}`
    let result = await new Promise ((reslove,reject)=>{
        return db.query(updateSql,(err,data)=>{
            if(err) console.log(err);
            reslove(data)
        })
    })
    ctx.body = "修改成功";
})



module.exports = journal;
